package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Carousel_ImageSrc;
import com.letv.whatslive.model.Chips;
import com.letv.whatslive.model.convert.Carousel_ImageSrcConvert;
import com.letv.whatslive.model.convert.ChipsConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by shenyue on 2016/7/5.
 */
@Repository
public class ChipsDAO extends BaseDAO{
    protected String collectionName = "chips";
    private static final Logger logger = LoggerFactory.getLogger(ChipsDAO.class);
    @Autowired
    private JedisDAO jedisDAO;
    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }


    public Chips getChipsById(Long id) {
        BasicDBObject query = new BasicDBObject();
        Chips chips = new Chips();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            chips = ChipsConvert.castDBObjectToChips(dbObject);
            setValueToChips(chips);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return chips;
    }

    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("createTime") != null) {
                query.put("createTime", ObjectUtils.toLong(params.get("createTime")));
            }
            if (params.get("updateTime") != null) {
                query.put("updateTime", ObjectUtils.toLong(params.get("updateTime")));
            }
            if (params.get("picUrl") != null) {
                query.put("picUrl", ObjectUtils.toString(params.get("picUrl")));
            }
            if (params.get("priority") != null) {
                query.put("priority", ObjectUtils.toLong(params.get("priority")));
            }
            if (params.get("tag") != null) {
                query.put("tag", ObjectUtils.toString(params.get("tag")));
            }

        }
        return query;
    }

    public List<Chips> getAllChipsByParams(Map<String, Object> orders,Map<String, Object> params){
        List<Chips> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Chips chips = ChipsConvert.castDBObjectToChips(dbObject);
                setValueToChips(chips);
                result.add(chips);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public List<Chips> getChipsListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<Chips> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Chips chips = ChipsConvert.castDBObjectToChips(dbObject);
                setValueToChips(chips);
                result.add(chips);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public List<Chips> getChipsListByParams(Map<String, Object> orders,Map<String, Object> params, Integer start, Integer limit) {
        List<Chips> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Chips chips = ChipsConvert.castDBObjectToChips(dbObject);
                setValueToChips(chips);
                result.add(chips);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Long countChipsByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    public void deleteChipsByParams(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }

    public Chips saveChips(Chips chips) {
        try {
            chips.setId(getAutoIncrementId());
            DBObject dbo = ChipsConvert.castChipsToDBObject(chips);
            WriteResult wr = this.dbCollection.insert(dbo);
            return chips;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public Boolean updateChips(Chips chips) {
        DBObject queryCondition = new BasicDBObject();
        Long chipsId = chips.getId();
        if(chipsId==null)
            return false;
        queryCondition.put("_id", chipsId); // 用来确定要修改的文档
        DBObject setValue = ChipsConvert.castChipsToDBObject(chips);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
        return true;
    }



    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {

        BasicDBObject order = new BasicDBObject();

        if(orders != null && orders.size() > 0){

            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        } else {

            //默认按照创建时间排序
            order.append("createTime", -1);
        }

        return order;
    }
    private void setValueToChips(Chips carousel_imageSrc) {
        carousel_imageSrc.setCreateTimeStr(carousel_imageSrc.getCreateTime() != null ?
                DateUtils.long2YMDHMS(carousel_imageSrc.getCreateTime()) : "");
        carousel_imageSrc.setUpdateTimeStr(carousel_imageSrc.getUpdateTime() != null ?
                DateUtils.long2YMDHMS(carousel_imageSrc.getUpdateTime()) : "");
    }
}
